class CatNav extends HTMLElement {
  navInfo = [
    {
      name: '首页',
      href: 'index.html'
    },
    {
      name: '爱猫TV',
      href: 'aimaoTV.html'
    },
    {
      name: '爱猫区',
      href: 'aimaoqu.html'
    },
    {
      name: '爱猫音乐',
      href: 'aimaoyinyue.html'
    }
  ];

  constructor() {
    super();

    // 创建 shadow DOM（可选，但推荐用于封装样式）
    const shadow = this.attachShadow({ mode: 'open' });

    // 创建图片
    this.img = document.createElement('img');
    this.img.src = this.getAttribute('src');
    this.img.style.height = '80%';
    this.img.style.marginLeft = '20px';

    // 创建导航栏容器
    this.nav = document.createElement('nav');
    this.nav.style.height = '100%';
    this.nav.style.display = 'flex';
    this.nav.style.justifyContent = 'center';
    this.nav.style.alignItems = 'center';
    this.nav.style.fontSize = '20px';
    this.nav.style.color = 'white';
    this.nav.style.cursor = 'pointer';

    // 动态渲染 navInfo 数据
    this.renderNav();

    // 父容器样式（flex 布局）
    const wrapper = document.createElement('div');
    wrapper.style.display = 'flex';
    wrapper.style.justifyContent = 'space-between';
    wrapper.style.alignItems = 'center';
    wrapper.style.height = '70px';
    wrapper.style.width = '100%';
    wrapper.style.backgroundColor = 'var(--cat-orange)'; // 导航背景色

    // 添加 img 和 nav 到 wrapper 中
    wrapper.appendChild(this.img);
    wrapper.appendChild(this.nav);

    // 把 wrapper 放入 shadow DOM
    shadow.appendChild(wrapper);
  }

  renderNav() {
    this.nav.innerHTML = ''; // 清空旧内容
    this.navInfo.forEach(item => {
      const a = document.createElement('a');
      a.textContent = item.name;
      a.href = item.href;
      a.style.margin = '0 15px';
      a.style.textDecoration = 'none';
      a.style.color = 'white';
      a.addEventListener('mouseover', () => {
        a.style.textDecoration = 'underline';
      });
      a.addEventListener('mouseout', () => {
        a.style.textDecoration = 'none';
      });
      this.nav.appendChild(a);
    });
    //获取属性nav-index
    const navIndex = this.getAttribute('nav-index');
    //判断this.navInfo[navIndex]是否存在
    if (this.navInfo[navIndex]) {
      this.nav.children[navIndex].style.color = 'var(--cat-text-one)';
    } else {
      console.error('nav-index 超出范围或不存在');
    }
  }
}

export default CatNav;